//
//  RecordViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "RecordViewController.h"
#import "TYLevelsView.h"
#import "WCLRecordEngine.h"
#import "TYLevelPairs.h"
#import "TYMemo.h"
#import <AVFoundation/AVFoundation.h>
#import "CustomAlertView.h"
#import "XYWSoundChanger.h"
#import "PlayAudioViewController.h"
#import "FMAudioPlayer.h"
#import "FileManager.h"
#import "CustomRecordModel.h"

@interface RecordViewController ()<WCLRecordEngineDelegate>{
    NSInteger                  currentTime;
    BOOL                       isRecording;
}

@property (weak, nonatomic) IBOutlet UIButton *actionBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *line;
@property (weak, nonatomic) IBOutlet UIView *buttonView;
@property (weak, nonatomic) IBOutlet UILabel *infoLabel;
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) CADisplayLink *levelTimer;
@property (nonatomic, strong) TYLevelsView *levelsView;
@property (nonatomic, strong) WCLRecordEngine *recordEngine;
@property (nonatomic, strong) CustomRecordModel *customRecord;

@end

@implementation RecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.titleStr) {
        self.title = self.titleStr;
    } else {
        self.title = @"录音";
    }
    [self addBackBtn];
    currentTime = 0;
    
    [self initView];
    
    //默认录音参数配置
    self.customRecord = [[CustomRecordModel alloc] init];
    self.customRecord.name = @"m4a";
    self.customRecord.fileType = AVFileTypeAppleM4A;
    self.customRecord.formatIdKey = kAudioFormatMPEG4AAC;
    self.customRecord.rate = 44100.0;
    self.customRecord.channels = 1;
    self.customRecord.quality = AVAudioQualityMedium;
        
    if ([self checkMicrophonePermission]) {
//        [self start];
    }
    
    [self showTimeLabel:currentTime];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self resetPress];
}

- (void)start{
   // 开始录制
   AVAudioSession *audioSession = [AVAudioSession sharedInstance];
   NSError *error;
   if (@available(iOS 10.0, *)) {
       if (![audioSession setCategory:AVAudioSessionCategoryRecord mode:AVAudioSessionModeDefault options:AVAudioSessionCategoryOptionMixWithOthers error:&error]) {
           NSLog(@"Category Error: %@",[error localizedDescription]);
       }
   } else {
       // Fallback on earlier versions
       if (![audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error]) {
           NSLog(@"Category Error: %@",[error localizedDescription]);
       }
   }
    if (![audioSession setActive:YES error:&error]) {
        NSLog(@"Activation Error: %@",[error localizedDescription]);
    }
    if (self.recordEngine.isPaused) {
        [self.recordEngine resumeCapture];
    } else {
        [self.recordEngine startUp];
        [self.recordEngine startCapture];
    }
    [self startTimer];
    [self startMeterTimer];
}

- (void)enterBackStop {
    [self resetPress];
}

- (IBAction)resetPress {
    self.actionBtn.selected = NO;
    [self.recordEngine shutdown];
    [self stopTimer];
    [self.recordEngine stopVoiceQueue];
    currentTime = 0;
    [self showTimeLabel:currentTime];
    
    [self stopMeterTimer];
    [self.levelsView resetLevelMeter];
    self.levelsView.frame = CGRectMake(SCREEN_WIDTH_DEVICE+2, IS_iPhoneX_Top + NavBarHeight + 90, SCREEN_WIDTH_DEVICE, 120);
}

- (IBAction)actionPress {
    self.actionBtn.selected = !self.actionBtn.selected;
    if (!self.actionBtn.selected) {
        [self.recordEngine pauseCapture];
        [self stopTimer];
    }else{
        [self start];
    }
}

- (IBAction)donePress {
    [self stopAction];
}


- (TYLevelsView *)levelsView {
    if (nil == _levelsView) {
        _levelsView = [[TYLevelsView alloc] init];
    }
    return _levelsView;
}


#pragma mark - timeTimer
- (void)startTimer {
    if (!isRecording) {
        isRecording = YES;
        self.timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
}

- (void)stopTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
        isRecording = NO;
    }
}

- (void)updateTime {
    currentTime = currentTime + 1;
    [self showTimeLabel:currentTime];
}

- (void)showTimeLabel:(NSInteger)total {
    NSInteger hours = (total / 3600);
    NSInteger minutes = (total / 60) % 60;
    NSInteger seconds = total % 60;
    self.timeLabel.text = [NSString stringWithFormat:@"%02li:%02li:%02li",(long)hours,(long)minutes,(long)seconds];
}


#pragma mark - LevelTimer
- (void)startMeterTimer {
    [self.levelTimer invalidate];
    self.levelTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateMeter)];
    self.levelTimer.frameInterval = 6;
    [self.levelTimer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)stopMeterTimer {
    [self.levelTimer invalidate];
    self.levelTimer = nil;
    [self.levelsView resetLevelMeter];
}

- (void)updateMeter {
    if (self.timer) {
        TYLevelPairs *levelPairs = [self.recordEngine levels];
        self.levelsView.level = levelPairs.linearLevel;
        self.levelsView.peakLevel = levelPairs.linearPeakLevel;
        self.levelsView.levelPairs = levelPairs;
        [self.levelsView setNeedsDisplay];
    }
    
}

- (void)stopAction{
    self.recordEngine.typeStr = self.titleStr;
    [self.recordEngine stopCaptureHandler:^(NSString *audioPath, LocalRecordModel *model) {        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self stopTimer];
            [self stopMeterTimer];
            [self.levelsView resetLevelMeter];
            self.levelsView.frame = CGRectMake(SCREEN_WIDTH_DEVICE+2, IS_iPhoneX_Top + NavBarHeight + 90, SCREEN_WIDTH_DEVICE, 120);
            [self goNextViewCon:model];
        });
        
    }];
}

- (void)goNextViewCon:(LocalRecordModel *)model {
    PlayAudioViewController *viewCon = [[PlayAudioViewController alloc] initWithNibName:@"PlayAudioViewController" bundle:nil];
    viewCon.model = model;
    viewCon.dismissBack = YES;
    [self.navigationController pushViewController:viewCon animated:YES];
}

- (BOOL)checkMicrophonePermission{
    __block BOOL bCanRecord = NO;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
        AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {// 未询问用户是否授权
            if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
                [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                    if (granted) {//用户选择允许
                        bCanRecord = YES;
                    } else {//用户选择不允许
                        bCanRecord = NO;
                    }
//                    self->allowMicrophonePermission = bCanRecord;
                }];
            }
        } else if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {
            bCanRecord = NO;//用户在第一次系统弹窗后选择不允许之后，再次录音的时候会走这里“麦克风权限未授权”
            // 未授权
            [self showGoSetting:@"开启【麦克风权限】后，才能正常答题：【设置】-【赏金侠】-【麦克风】开启"];
        } else{
            bCanRecord = YES;
            // 已授权
        }
    }
    return bCanRecord;
}

- (void)showGoSetting:(NSString *)errorStr{
    CustomAlertView *alertView = [[CustomAlertView alloc] initItem:errorStr withButtons:[NSArray arrayWithObjects:@"放弃", @"去设置", nil]];
    alertView.SureHandle = ^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success) {}];
    };
    alertView.CancelHandle = ^{
        [self goBackAction];
    };
    [alertView show];
}

- (void)initView {
    self.levelsView.frame = CGRectMake(SCREEN_WIDTH_DEVICE+2, IS_iPhoneX_Top + NavBarHeight + 90, SCREEN_WIDTH_DEVICE, 120);
    [self.view addSubview:self.levelsView];
    
    [self.line setFrame:CGRectMake(0, self.levelsView.frame.origin.y + 58, SCREEN_WIDTH_DEVICE, 2)];
    self.line.image = [self drawLineOfDashByImageView:self.line];

    [self.timeLabel setFrame:CGRectMake(0, CGRectGetMaxY(self.levelsView.frame) + 100, SCREEN_WIDTH_DEVICE, 44)];
    [self.buttonView setFrame:CGRectMake((SCREEN_WIDTH_DEVICE-320)/2.0, CGRectGetMaxY(self.timeLabel.frame)+30, 320, 70)];
    [self.typeLabel setFrame:CGRectMake(0, CGRectGetMaxY(self.buttonView.frame)+30, SCREEN_WIDTH_DEVICE, 20)];
    [self.infoLabel setFrame:CGRectMake(0, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Bottom - 40, SCREEN_WIDTH_DEVICE, 21)];
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error;
    if (![audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error]) {
        NSLog(@"Category Error: %@",[error localizedDescription]);
    }
    if (![audioSession setActive:YES error:&error]) {
        NSLog(@"Activation Error: %@",[error localizedDescription]);
    }
}

- (WCLRecordEngine *)recordEngine {
    if (_recordEngine == nil) {
        _recordEngine = [[WCLRecordEngine alloc] init];
        _recordEngine.recordModel = self.customRecord;
        _recordEngine.delegate = self;
        _recordEngine.needSave = YES;
    }
    return _recordEngine;
}

- (UIImage *)drawLineOfDashByImageView:(UIImageView *)imageView {
    // 开始划线 划线的frame
    UIGraphicsBeginImageContext(imageView.frame.size);
    [imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)];
    // 获取上下文
    CGContextRef line = UIGraphicsGetCurrentContext();
    // 设置线条终点的形状
    CGContextSetLineCap(line, kCGLineCapRound);
    // 设置虚线的长度 和 间距
    CGFloat lengths[] = {2,2};
    CGContextSetStrokeColorWithColor(line, WaringColor.CGColor);
    // 开始绘制虚线
    CGContextSetLineDash(line, 0, lengths, 2);
    CGContextMoveToPoint(line, 0.0, 2.0);
    CGContextAddLineToPoint(line, SCREEN_WIDTH_DEVICE, 2.0);
    CGContextStrokePath(line);
    // UIGraphicsGetImageFromCurrentImageContext()返回的就是image
    return UIGraphicsGetImageFromCurrentImageContext();
}
@end
